package org.emergency.framework.filter;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.emergency.framework.constant.SessionConstant;

/**
 * 权限过滤类，对每一个请求，都过滤一下
 * 
 * @author game
 * 
 */
public class SecurityManagerFilter implements Filter {
	
	Logger log = Logger.getLogger(this.getClass());

	private String[] excludeURL;

	@Override
	public void doFilter(ServletRequest servletRequest,
			ServletResponse response, FilterChain arg2) throws IOException,
			ServletException {
		HttpServletRequest localHttpServletRequest = (HttpServletRequest)servletRequest;
		log.info("filter 测试BEGIN");
		
		Enumeration localObject1 = localHttpServletRequest.getHeaderNames();
	      int i = 0;
	      String str1="";
	      Object localObject3;
	      Object localObject2;
	      String str6;
	      while (((Enumeration)localObject1).hasMoreElements()) {
	        localObject2 = (String)((Enumeration)localObject1).nextElement();
	        localObject3 = localHttpServletRequest.getHeaders((String)localObject2);
	        while (((Enumeration)localObject3).hasMoreElements()) {
	          str6 = (String)((Enumeration)localObject3).nextElement();
	          str1 += str1 + (String)localObject2 + ":" + str6 + "\n";
	        }
	        ++i;
	      }
	      String CharacterEncoding = localHttpServletRequest.getCharacterEncoding();
	      String contenttypeString = localHttpServletRequest.getContentType();
	      
//	      log.info("head:"+str1); 
	      log.info("CharacterEncoding:"+CharacterEncoding);
	      log.info("contenttypeString:"+contenttypeString);
		  
		log.info("filter 测试END");
		
		
		
		

		System.out.println("---------doFilter-----------");
		HttpServletRequest request = (HttpServletRequest) servletRequest;

		HttpSession session = request.getSession(false);
		String currentURL = request.getRequestURI(); // 取得根目录所对应的绝对路径
		String targetURL = currentURL.substring(currentURL.indexOf("/", 1),
				currentURL.length()); // 截取到当前文件名用于比较

		HttpServletResponse response1 = (HttpServletResponse)response;
		
		// 判断当前页是否是重定向以后的登录页面，如果是就不做session的判断，防止出现死循环
		if (!isHave(excludeURL, targetURL)) {
			// 用户登录以后才添加session
			if (session == null
					|| session.getAttribute(SessionConstant.UserSession) == null) {
				response1.sendRedirect(request.getContextPath()
						+ excludeURL[0]);
				// 如果session为空，表示用户没有登录就重定向到配置的第一个页面
				return;
			}
		}
		
		arg2.doFilter(servletRequest, response);// 这句是关键，没有的话就把servlet过滤了，可以如servlet一样设置跑到自己想要的页面
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		String cfgStr = filterConfig.getInitParameter("excludeURL");
		// 如果为空，就初始化字符串链接
		if (cfgStr == null || cfgStr.trim().equals("")) {
			excludeURL = new String[2];
			excludeURL[0] = "/login.jsp";
			excludeURL[1] = "/admin/LoginOut_checkLogin.action";
		} else {
			excludeURL = cfgStr.split(",");
		}
	}

	@Override
	public void destroy() {
		excludeURL = null;
	}

	/**
	 * 判断字符串数组里是否有dest字符串
	 * 
	 * @param origin
	 *            数组，一个字符串数组
	 * @param dest
	 *            字符串
	 * @return
	 */
	private boolean isHave(String[] origin, String dest) {
//		for (String str : origin) {
//			if (str.indexOf(dest) != -1) {
//				return true;
//			}
//		}
		for (int i = 0; i < origin.length; i++) {
			if (origin[i].indexOf(dest) != -1) {
				return true;
			}
			
		}
		return false;
	}

}
